package tlcn.app;

import java.sql.Date;
import java.util.ArrayList;
import java.util.List;
import tlcn.business.ManagerData;
import tlcn.data.Dish;
import tlcn.data.Material;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import com.keyes.youtube.OpenYouTubePlayerActivity;
import tlcn.*;


public class GuideActivity extends Activity{
	
	ManagerData data;
	String linkVideo;
	String DishID;
	String date;
	String name;
	String meal="Bữa sáng";
	Button btnSetup;
	Button btnDate;
	TextView txtDate;
	Date dateSelect;
	int number=1;
	Spinner spinMeal,spinNumber;
	ManagerData managerData;
	Activity context;
	LinearLayout l;
	ImageView btnPlay;
	
	VideoView videoView;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_guide_dishes);
		context=this;
		linkVideo=getIntent().getExtras().getString("linkVideo");
		DishID=getIntent().getExtras().getString("DishID");
		date=getIntent().getExtras().getString("date");
		name=getIntent().getExtras().getString("name");
		setTitle(name);
		l=(LinearLayout)findViewById(R.id.tabVideo);
		//videoView = (VideoView) findViewById(R.id.videoView1);
		btnPlay=(ImageView) findViewById(R.id.btnPlay);
		loadTab();
	
	}
	private void startVideo(String videoID) {
		 
		 Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse("vnd.youtube:" + videoID));
		 List<ResolveInfo> list = getPackageManager().queryIntentActivities(i, PackageManager.MATCH_DEFAULT_ONLY);
		 if (list.size() == 0) {
		  i = new Intent(getApplicationContext(),OpenYouTubePlayerActivity.class);
		  i.putExtra("VIDEO_ID", videoID);
		 }
		 startActivity(i);
	}
	private void loadTab(){
		final TabHost tab=(TabHost) findViewById (android.R.id.tabhost);
		tab.setup();
		TabHost.TabSpec spec;
		//Tạo tab1
		spec=tab.newTabSpec("t1");
		spec.setContent(R.id.tabMaterials);
		spec.setIndicator("Nguyên Liệu");
		tab.addTab(spec);
		doWidgetsTab1();
		
		//Tạo tab2
		spec=tab.newTabSpec("t2");
		spec.setContent(R.id.tabGuide);
		spec.setIndicator("Hướng Dẫn");
		tab.addTab(spec);
		doWidgetsTab2();
		//Tạo tab3
		spec=tab.newTabSpec("t3");
		spec.setContent(R.id.tabVideo);
		spec.setIndicator("Video");
		tab.addTab(spec);
		final TextView tv= (TextView) findViewById(R.id.txtDishName);
		tv.setText("Khẩu phần: ");
		final String link=linkVideo.substring(31);
	
		btnPlay.setOnClickListener(new OnClickListener(){
            //http://www.youtube.com/watch?v=x7BiGpvOLqw
            @Override
            public void onClick(View v) {
            	//Toast.makeText(context, tv.getText()+link , Toast.LENGTH_SHORT).show();
				startVideo(link);
            }
    }); 
		//phần đặt lịch
		spinMeal=(Spinner) findViewById(R.id.spinMeal);
		List<String> array = new ArrayList<String>();
		array.add("Bữa sáng");
		array.add("Bữa trưa");
		array.add("Bữa tối");
		ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
				GuideActivity.this,
				android.R.layout.simple_spinner_item,
				array);
		arrayAdapter.setDropDownViewResource(android.R.layout.simple_list_item_single_choice);
		spinMeal.setAdapter(arrayAdapter);
		spinMeal.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int pos, long id) {
				meal=parent.getItemAtPosition(pos).toString();
				if(managerData.checkSetup(dateSelect.toString(),DishID,meal))
					btnSetup.setEnabled(true);
			}
			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
			}
		});
		txtDate=(TextView) findViewById(R.id.txtDate);
		txtDate.setText(date);
		String strArrtmp[]=date.split("/");
		int ngay=Integer.parseInt(strArrtmp[0]);
		int thang=Integer.parseInt(strArrtmp[1]);
		int nam=Integer.parseInt(strArrtmp[2]);
		dateSelect=Date.valueOf(nam+"-"+thang+"-"+ngay);
		btnSetup=(Button) findViewById(R.id.btnDat);
		managerData= new ManagerData(getApplicationContext());
		if(!managerData.checkSetup(dateSelect.toString(),DishID,meal))
			btnSetup.setEnabled(false);
		btnDate=(Button) findViewById(R.id.btnDate);
		btnDate.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				showDatePickerDialog();
			}
		});
		btnSetup.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				btnSetup.setEnabled(false);
				AlertDialog.Builder builder = new AlertDialog.Builder(GuideActivity.this);
                builder.setMessage("Bạn đã thêm thành công món "+name+" vào "+meal+" ngày "+txtDate.getText());
                builder.setCancelable(false);
//                builder.setPositiveButton("Xem",
//                        new DialogInterface.OnClickListener() {
//                            public void onClick(DialogInterface dialog, int id) {
//                            	Intent intent= new Intent(GuideActivity.this,SetActivity.class);
//                            	intent.putExtra("date", date);
//                            	context.startActivity(intent);
//                            	context.finish();
//                            }
//                        });
                builder.setNegativeButton("Tiếp tục",null);
                AlertDialog alertDialog = builder.create();
				if(managerData.addSetup(dateSelect.toString(),DishID,meal))
					alertDialog.show();
			}
		});
	}
	ListView listViewDish;
	ArrayAdapter<String> adapter;
	List<String> listAdapter;
	
	private void doWidgetsTab1(){
		data= new ManagerData(this);
		listViewDish= (ListView) findViewById(R.id.listViewDish);
		spinNumber=(Spinner) findViewById(R.id.spinNumber);
		String[] array = {"1", "2", "3", "4","5","6","7","8","9","10"};
		ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
				GuideActivity.this,
				android.R.layout.simple_spinner_item,
				array);
		arrayAdapter.setDropDownViewResource(android.R.layout.simple_list_item_single_choice);
		spinNumber.setAdapter(arrayAdapter);
		spinNumber.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int pos, long id) {
				number=Integer.parseInt((String) parent.getItemAtPosition(pos));
				UpdateAdapter();
				adapter.notifyDataSetChanged(); 
			}
			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
			}
		}); 
		listAdapter= new ArrayList<String>();
		UpdateAdapter();
		adapter= new ArrayAdapter<String>(this,android.R.layout.simple_spinner_dropdown_item,listAdapter);
		listViewDish.setAdapter(adapter);
		
		spinNumber.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int pos, long id) {
				number=Integer.parseInt((String) parent.getItemAtPosition(pos));
				UpdateAdapter();
				adapter.notifyDataSetChanged();
			}
			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
			}
		});
		listAdapter= new ArrayList<String>();
		UpdateAdapter();
		adapter= new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,listAdapter);
		listViewDish.setAdapter(adapter);
	}
	private void UpdateAdapter(){
		ArrayList<Material> materials = data.getMaterialOfDish(DishID);
		listAdapter.clear();
		String gv="Gia vi: ";
		for (Material m : materials) {
			if(m.getUnit()==null)
				//listAdapter.add(m.getMaterialName());
				gv+=m.getMaterialName()+", ";
			else
				listAdapter.add((m.getWeight()*number)+" "+m.getUnit()+" "+m.getMaterialName());
		}		
		gv=gv.substring(0,gv.length()-2);
		listAdapter.add(gv);
	}
	private void doWidgetsTab2(){
		WebView guide= (WebView) findViewById(R.id.webView1);
		String data=getIntent().getExtras().getString("guide");
		guide.loadData(data,"text/html;charset=utf-8",null);
	}
	public void showDatePickerDialog()
	{
		OnDateSetListener callback=new OnDateSetListener() {
			public void onDateSet(DatePicker view, int year,
					int monthOfYear,int dayOfMonth) {
				txtDate.setText((dayOfMonth) +"/"+(monthOfYear+1)+"/"+year);
				dateSelect=Date.valueOf(year+"-"+(monthOfYear+1)+"-"+dayOfMonth);
				if(managerData.checkSetup(dateSelect.toString(),DishID,meal))
					btnSetup.setEnabled(true);
				else
					btnSetup.setEnabled(false);
			}
		};
		String s=txtDate.getText()+"";
		String strArrtmp[]=s.split("/");
		int ngay=Integer.parseInt(strArrtmp[0]);
		int thang=Integer.parseInt(strArrtmp[1])-1;
		int nam=Integer.parseInt(strArrtmp[2]);
		DatePickerDialog pic=new DatePickerDialog(
				GuideActivity.this,callback,nam,thang,ngay);
		pic.setTitle("Chọn ngày đặt lịch nấu");
		pic.show();
	}
}
